package com.kingdee.eas.xbwebservice;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.util.db.SQLUtils;

/**
 * @author lifetime
 *
 */
public class UtilFacadeControllerBean extends AbstractUtilFacadeControllerBean {
	private static Logger logger = Logger.getLogger("com.kingdee.eas.xbwebservice.UtilFacadeControllerBean");

	protected void _executeUpdateSqlHasBytes(Context ctx, String sql, Object[] args) throws BOSException {
		Connection conn = getConnection(ctx);
		PreparedStatement stt = null;
		try {
			stt = conn.prepareStatement(sql);
			for (int i = 0, k = args.length; i < k; i++) {
				Object obj = args[i];
				if (obj instanceof byte[]) {
					stt.setBytes(i + 1, (byte[]) obj);
				} else {
					stt.setObject(i + 1, obj);
				}
			}
			stt.execute();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SQLUtils.cleanup(stt, conn);
		}
	}

	protected byte[] _getBytes(Context ctx, String sql, Object[] args) throws BOSException {
		Connection conn = getConnection(ctx);
		PreparedStatement stt = null;
		ResultSet res = null;
		try {
			stt = conn.prepareStatement(sql);
			for (int i = 0, k = args.length; i < k; i++) {
				Object obj = args[i];
				stt.setObject(i + 1, obj);
			}
			res = stt.executeQuery();
			if (res.next()) {
				Blob blob = res.getBlob(1);
				if (blob == null) {
					return null;
				}
				InputStream stream = blob.getBinaryStream();
				byte[] bs = new byte[(int) blob.length()];
				stream.read(bs);
				stream.close();
				return bs;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SQLUtils.cleanup(stt, conn);
		}
		return null;
	}
}